package com.zhangjun.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * security配置类
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        //拦截表单登录，
        http.formLogin()
                //放行login的登录页面
                .loginPage("/api/login.html")
                //登录按钮点击后放行login请求          找到的是login方法而不是接口
                .loginProcessingUrl("/login")
                //登录成功后返回main页面
                //.successForwardUrl("/toMain")
                //自定义登录成功跳转逻辑
                .successHandler(new MyAuthenticationSuccessHandler("http://www.baidu.com"))
                //登录失败的结果
                //.failureForwardUrl("/toError")
                .failureHandler(new MyAuthenticationFailureHandler("/error.html"))
                //默认是username 自定义
                .usernameParameter("username")
                .passwordParameter("password");

        //授权放行页面
        http.authorizeRequests()
                //授权login页面
                .antMatchers("/api/login.html").permitAll()
                //授权失败页面
                .antMatchers("/api/error.html").permitAll()
                //ant表达式授权路径     *代表文件   **代表图片和文件
                //.antMatchers("/img/**").permitAll()
                //正则表达式         限制只能是post才能访问
                //.regexMatchers(HttpMethod.POST,".+[.]jpg").permitAll()
                //限制所有请求都要加/api
                .mvcMatchers("/img/**").servletPath("/api").permitAll()
                //所有页面都要经过授权才能访问
                .anyRequest().authenticated();
        //关闭csrf防护
        http.csrf().disable();
    }


}
